package com.shop.cloud.filter;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.lang3.StringUtils;

import com.shop.cloud.auth0.jwt.TokenGenerator;
import com.shop.cloud.auth0.jwt.interfaces.Claim;
import com.shop.cloud.util.CookieManager;
import com.shop.cloud.util.MagicConstants;

public class CheckPermission extends BodyTagSupport {

	private static final long serialVersionUID = 1L;
	
	private String code = null;

	public int doEndTag() throws JspException {
		JspWriter out = pageContext.getOut();
		HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
		String html=getBodyContent().getString();
		String token = request.getHeader(MagicConstants.USER_TOKEN);
		if (StringUtils.isEmpty(token)) {
			token = request.getParameter(MagicConstants.USER_TOKEN);
		}
		if (StringUtils.isEmpty(token)) {
			token = new CookieManager(request, null).getCookie(MagicConstants.USER_TOKEN);
		}
		Map<String, Claim> datas=null;
		if (StringUtils.isNotEmpty(token)) {
			try {
				datas=TokenGenerator.getClaims(token);
			} catch (Exception e) {
				e.printStackTrace();
				return SKIP_BODY;
			}
			List<String> auths=datas.get(MagicConstants.SESSION_USER_PERMISSIONS).asList(String.class);
			if (auths!=null && auths.contains( "/"+code)) {
				try {
					out.print(html);
				} catch (IOException e) {
					e.printStackTrace();
				}
				return EVAL_PAGE;
			}
		}
		return SKIP_BODY;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String permission) {
		this.code = permission;
	}

}